# -*- coding: utf-8 -*-
"""
@Time ： 2022/10/9 17:08
@Auth ： 司徒飞
@File ：utils_domain.py
@IDE ：PyCharm
"""


from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkcore.http.http_config import HttpConfig
from huaweicloudsdkdns.v2 import *
from ops.devops.utils.util_config import get_config
import json


class DomainOp(object):
    # 创建客户端
    @staticmethod
    def create_client():

        # 获取相关配置
        conf = get_config('cloud')

        # 初始化client
        config = HttpConfig.get_default_config()
        config.ignore_ssl_verification = True
        credentials = BasicCredentials(conf.get('access_id'), conf.get('access_secret'))

        client = DnsClient.new_builder() \
            .with_http_config(config) \
            .with_credentials(credentials) \
            .with_endpoint(conf.get('domain_endpoint')) \
            .build()
        return client

    # 列出zones
    @staticmethod
    def list_zones(client):
        try:
            request = ListPublicZonesRequest(limit=100)
            response = client.list_public_zones(request)
            res = response.zones
            print(res)
            return res
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
            return {}

    # 创建解析记录
    @staticmethod
    def create_record_set(client, zone_id, domain_name, domain_type, records):
        try:
            body = CreateRecordSetReq(name=domain_name, type=domain_type, records=records)
            request = CreateRecordSetRequest(zone_id=zone_id, body=body)
            print(request)
            client.create_record_set(request)
            msg = '域名:{0}解析添加成功，记录类型:{1}，记录值:{2}'.format(domain_name, domain_type, records)
            return {'code': 200, 'msg': msg}
        except exceptions.ClientRequestException as e:
            msg = '域名:{0}解析添加失败，原因:{1}，请关注'.format(domain_name, e.error_msg)
            print(msg)
            return {'code': 400, 'msg': msg}

    # 查询解析记录
    @staticmethod
    def get_record_sets(client):

        request = ListRecordSetsRequest()
        res = client.list_record_sets(request)
        print(res.recordsets)

        return {'code': 200, 'recordsets': res.recordsets}

